package com.tz.liveplayermodule;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.baijia.baijiashilian.liveplayer.ViETextureViewRenderer;
import com.baijiahulian.livecore.LiveSDK;
import com.baijiahulian.livecore.context.LPConstants;
import com.baijiahulian.livecore.context.LPError;
import com.baijiahulian.livecore.context.LiveRoom;
import com.baijiahulian.livecore.context.OnLiveRoomListener;
import com.baijiahulian.livecore.launch.LPLaunchListener;
import com.baijiahulian.livecore.listener.OnPhoneRollCallListener;
import com.baijiahulian.livecore.models.imodels.IAnnouncementModel;
import com.baijiahulian.livecore.models.imodels.ILoginConflictModel;
import com.baijiahulian.livecore.models.imodels.IMediaControlModel;
import com.baijiahulian.livecore.models.imodels.IMediaModel;
import com.baijiahulian.livecore.models.imodels.IMessageModel;
import com.baijiahulian.livecore.models.imodels.IUserInModel;
import com.baijiahulian.livecore.models.imodels.IUserModel;
import com.baijiahulian.livecore.ppt.LPPPTFragment;
import com.baijiahulian.livecore.utils.LPBackPressureBufferedSubscriber;
import com.baijiahulian.livecore.utils.LPErrorPrintSubscriber;
import com.baijiahulian.livecore.wrapper.LPPlayer;
import com.baijiahulian.livecore.wrapper.LPRecorder;
import com.google.gson.Gson;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tz.liveplayermodule.adapter.ListView1Adapter;
import com.tz.liveplayermodule.adapter.ListView3Adapter;
import com.tz.liveplayermodule.adapter.ListViewDownAdapter;
import com.tz.liveplayermodule.adapter.RecyclerAdapter;
import com.tz.liveplayermodule.adapter.RvDividerItemDecoration;
import com.tz.liveplayermodule.adapter.SecondaryListAdapter;
import com.tz.liveplayermodule.bean.ClassListBean;
import com.tz.liveplayermodule.bean.GetLiveRoomAppBean;
import com.tz.liveplayermodule.bean.GetNodesBean;
import com.tz.liveplayermodule.bean.GetVideoUrl;
import com.tz.liveplayermodule.bean.IntroBean;
import com.tz.liveplayermodule.bean.PlayBackListBean;
import com.tz.liveplayermodule.bean.RalationDownloads;
import com.tz.liveplayermodule.bean.SignBean;
import com.tz.liveplayermodule.downloadUtil.DownLoadObserver;
import com.tz.liveplayermodule.downloadUtil.DownloadInfo;
import com.tz.liveplayermodule.downloadUtil.DownloadManager;
import com.tz.liveplayermodule.greendao.db.DownloadInfoDao;
import com.tz.liveplayermodule.greendao.db.GreenDaoManager;
import com.tz.liveplayermodule.jcvideoplayer.JCVideoPlayer;
import com.tz.liveplayermodule.util.CommonUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

//视频播放
//https://www.jianshu.com/p/6715025607e8
//https://www.jianshu.com/p/300baf90a13e
//二级列表
//https://www.jianshu.com/p/840e6578555a
//https://www.jianshu.com/p/46625fc9cb6e

public class LiveRoomNewActivity extends FragmentActivity implements View.OnClickListener {
    private int BACK_VIDEO = 0;
    private int LIVE_VIDEO = 1;
    private int FULL_SCREEN_LIVE_VIDEO_BACK = 1003;

    private Subscription subscription;
    private LiveRoom liveRoom;
    private RelativeLayout videoLayout;
    private FrameLayout recorderLayout;
    private TextureView textureView;
    private LinearLayout liveRoomLayout, liveRoomContentLayout;
    private TextView liveRoomContent;
    private LPRecorder recorder; // recorder用于发布本地音视频
    private LPPlayer player; // player用于播放远程音视频流
    private AlertDialog dialog;
    private String content, contentUrl;
    private TextView text1, text2, text3;
    private View view1, view2, view3;
    private RelativeLayout layout_bottom1;
    private LinearLayout layout1, layout_bottom, layout_bottom2, layout_bottom3, down_layout;
    private TextView item_title;
    private ImageView close_down;
    private List<IMessageModel> iMessageModelList;
    private ListView1Adapter listView1Adapter;
    private List<ClassListBean.ResultBean.ListBean> listView2List;
    private List<PlayBackListBean> playBackListBeanList;
    private Map<Integer, List<PlayBackListBean>> playBackListMap;
    private List<SecondaryListAdapter.DataTree> dataTreeList;
    private RecyclerAdapter recyclerAdapter;
    private RecyclerView listview2;
    private ListView listview1, down_listview;
    private EditText etMessage;
    private ImageView back_img, share_img, down_video_img, full_screen_img, change_size_img;
    private LinearLayout change_size_layout;
    private ImageView change_size_img1, change_size_img2, change_size_img3, change_size_img4;
    private int datePosition = 0;
    private AlertDialog progressDialog;
    private boolean isPlayVideo;
    private String userId = "";
    private View videoController;
    private ListView3Adapter listView3Adapter;
    private ListViewDownAdapter listViewDownAdapter;
    private List<RalationDownloads.ResultBean> resultBeanList;
    private List<String> pptImgList;
    private DownloadInfoDao downloadInfoDao;
    private boolean playNextVideo;//播放下一条视频
    private String playId;
    private PowerManager.WakeLock wakeLock;
    private boolean hasPower;

    // APP_ID 替换为你的应用从官方网站申请到的合法appID
    private static final String APP_ID = "wx86c4a72d01af74a0";

    // IWXAPI 是第三方app和微信通信的openApi接口
    private static IWXAPI api;

    private VideoView videoView;
    private MediaController mController;
    private MediaPlayer mediaPlayer;
    private ImageButton fullScreenImage;
    private LinearLayout loadingView;
    private String videoPath;
    private int playCurrent;

    private void regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        // 将应用的appId注册到微信
        api.registerApp(APP_ID);
    }

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            //如果系统回收的Activity， 但是系统却保留了Fragment， 当Activity被重新初始化， 此时， 系统保存的Fragment 的getActivity为空，
            //所以要移除旧的Fragment ， 重新初始化新的Fragment
            String FRAGMENTS_TAG = "android:support:fragments";
            savedInstanceState.remove(FRAGMENTS_TAG);
        }
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_live_room_new);

//        if (!isTaskRoot()) {
//            finish();
//            return;
//        }

        downloadInfoDao = GreenDaoManager.getInstance(this).getNewSession().getDownloadInfoDao();

        List<DownloadInfo> downloadingInfoList = new ArrayList<>();
        downloadingInfoList.addAll(downloadInfoDao.queryBuilder()
                .where(DownloadInfoDao.Properties.CompleteType.eq("1")).list());

        for (DownloadInfo downloadInfo : downloadingInfoList) {
            downLoadFile(0, downloadInfo.getUrl(), downloadInfo.getFileId());
        }

        //保持屏幕唤醒
        CommonUtils.keepScreenOn(wakeLock, this, true);
        CommonUtils.keepScreenLongLight(this, true);
        regToWx();
        initView();
        initVideoView();

        buildProgressDialog(false);

        if (getIntent().getIntExtra("new", 0) == BACK_VIDEO) {
            getNodes();
//            getIntro(getIntent().getStringExtra("course_id"), false);
        } else {
            getLiveRoomApp();
//            getSign("19030262530951");
        }

        showView(2);
        layout1.setVisibility(View.GONE);
        layout_bottom1.setVisibility(View.GONE);
        recorderLayout.setVisibility(View.GONE);
        videoController.setVisibility(View.VISIBLE);
        down_video_img.setVisibility(View.VISIBLE);
        full_screen_img.setVisibility(View.GONE);
    }

    private void initVideoView() {
        videoView = findViewById(R.id.video_view);
        fullScreenImage = findViewById(R.id.full_screen_image);
        loadingView = findViewById(R.id.loading_view);
        fullScreenImage.setOnClickListener(this);

        mController = new MediaController(this);
        videoView.setMediaController(mController);
        mController.setMediaPlayer(videoView);

        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mMediaPlayer) {
                mediaPlayer = mMediaPlayer;
                videoView.start();
                loadingView.setVisibility(View.GONE);
                fullScreenImage.setVisibility(View.VISIBLE);
            }
        });
    }

    public void startCurVideoView() {
        System.out.println("videoPath==:" + videoPath);
        loadingView.setVisibility(View.VISIBLE);
        fullScreenImage.setVisibility(View.GONE);
        videoView.setVideoPath(videoPath);
    }

    /**
     * 统一检测权限接口
     */
    private void checkPrivilegeIsFree(String itemId) {
        String type;
        if (getIntent().getIntExtra("new", 0) == 0) {
            type = "1";
        } else {
            type = "4";
        }

        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("token", getIntent().getStringExtra("token"));
        formBody.add("type", type);
        formBody.add("id", getIntent().getStringExtra("course_id"));
        formBody.add("item", itemId);
        Request request = new Request.Builder()//创建Request 对象。
                .url(getIntent().getStringExtra("urlTitle") + "/api.php?c=Ucenter&a=checkPrivilegeIsFree")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                cancelProgressDialog();
                LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LiveRoomNewActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
                    }
                });
                setFinish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                cancelProgressDialog();
                assert response.body() != null;
                String responseStr = response.body().string();
                System.out.println("checkPrivilegeIsFree==:" + responseStr);
                Gson gson = new Gson();
                final IntroBean introBean = gson.fromJson(responseStr, IntroBean.class);
                if (introBean.getCode() != null && introBean.getCode() == 200) {
                    LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            hasPower = true;
                        }
                    });
                } else {
                    hasPower = false;
                }

                //todo
//                hasPower = true;
            }
        });
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.back_img) {
            setFinish();
        } else if (i == R.id.share_img) {
            WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
            miniProgramObj.webpageUrl = "http://www.qq.com"; // 兼容低版本的网页链接
            miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
            miniProgramObj.userName = getIntent().getStringExtra("username");     // 小程序原始id
//            miniProgramObj.userName = "gh_96c7706f8ae6";     // 小程序原始id
//            miniProgramObj.path = "/player/pages/live/playback?id=xx";            //小程序页面路径
            WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
            msg.title = "老妖精学员端";                    // 小程序消息title
            msg.description = "老妖精学员端";               // 小程序消息desc
            msg.thumbData = CommonUtils.Bitmap2Bytes(BitmapFactory.decodeResource(getResources(), R.drawable.icon));                      // 小程序消息封面图片，小于128k

            SendMessageToWX.Req req = new SendMessageToWX.Req();
//            req.transaction = buildTransaction("miniProgram");
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
            api.sendReq(req);

            //初始化一个 WXTextObject 对象，填写分享的文本内容
//            WXTextObject textObj = new WXTextObject();
//            textObj.text = "电脑端听课地址：lyj.top";
//            WXMediaMessage msg = new WXMediaMessage();
//            msg.mediaObject = textObj;
//            msg.description = "电脑端听课地址：lyj.top";
//            SendMessageToWX.Req req = new SendMessageToWX.Req();
//            req.transaction = String.valueOf(System.currentTimeMillis());
//            req.message = msg;
//            req.scene = WXSceneSession;
//            api.sendReq(req);
        } else if (i == R.id.down_video_img) {
            RxPermissions rxPermissions = new RxPermissions(this);
            rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(new Observer<Boolean>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Boolean aBoolean) {
                            if (aBoolean) {
                                if (down_layout.getVisibility() == View.GONE) {
                                    layout_bottom.setVisibility(View.GONE);
                                    down_layout.setVisibility(View.VISIBLE);
                                    buildProgressDialog(false);
                                    getRalationDownloads();
                                } else {
                                    layout_bottom.setVisibility(View.VISIBLE);
                                    down_layout.setVisibility(View.GONE);
                                }
                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else if (i == R.id.full_screen_img) {
            RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) videoLayout.getLayoutParams();

            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                linearParams.height = CommonUtils.getScreenHeight(LiveRoomNewActivity.this) / 3;
                linearParams.width = CommonUtils.getScreenWidth(LiveRoomNewActivity.this);
                //切换竖屏
                LiveRoomNewActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            } else {
                linearParams.height = CommonUtils.getScreenHeight(LiveRoomNewActivity.this);
                linearParams.width = CommonUtils.getScreenWidth(LiveRoomNewActivity.this);
                //切换横屏
                LiveRoomNewActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
            videoLayout.setLayoutParams(linearParams);
        } else if (i == R.id.full_screen_image) {
//            videoView.pause();
            System.out.println(" videoView.getCurrentPosition():" + videoView.getCurrentPosition());
            System.out.println(" mediaPlayer.getCurrentPosition():" + mediaPlayer.getCurrentPosition());

            Intent intent = new Intent(LiveRoomNewActivity.this, FullScreenLiveVideoActivity.class);
            intent.setFlags(10002);
            intent.putExtra("filePath", videoPath);
            intent.putExtra("Current", videoView.getCurrentPosition());
            startActivityForResult(intent, FULL_SCREEN_LIVE_VIDEO_BACK);

//            RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) videoController.getLayoutParams();
//
//            if (isVertical) {
//                isVertical = false;
//                videoView.setRotation(90);
//                linearParams.height = CommonUtils.getScreenHeight(LiveRoomNewActivity.this);
//                linearParams.width = CommonUtils.getScreenWidth(LiveRoomNewActivity.this);
//
//                videoView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT);
//            } else {
//                isVertical = true;
//                videoView.setRotation(0);
//                linearParams.height = CommonUtils.getScreenHeight(LiveRoomNewActivity.this) / 3;
//                linearParams.width = CommonUtils.getScreenWidth(LiveRoomNewActivity.this);
//            }
//            videoController.setLayoutParams(linearParams);


//            if (videoView == null) {
//                return;
//            }
//
//            System.out.println("fullScreenImage");
//
//            RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) videoLayout.getLayoutParams();
//
//            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
//                linearParams.height = CommonUtils.getScreenHeight(LiveRoomNewActivity.this) / 3;
//                linearParams.width = CommonUtils.getScreenWidth(LiveRoomNewActivity.this);
//                //切换竖屏
//                LiveRoomNewActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//            } else {
//                linearParams.height = CommonUtils.getScreenHeight(LiveRoomNewActivity.this);
//                linearParams.width = CommonUtils.getScreenWidth(LiveRoomNewActivity.this);
//                //切换横屏
//                LiveRoomNewActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//            }
//            videoLayout.setLayoutParams(linearParams);
        } else if (i == R.id.close_down) {
            layout_bottom.setVisibility(View.VISIBLE);
            down_layout.setVisibility(View.GONE);
        } else if (i == R.id.down_all_text) {
            for (RalationDownloads.ResultBean resultBean : resultBeanList) {
                if (resultBean.getType() == 0) {
                    DownloadInfo note = new DownloadInfo();
                    note.setUrl(resultBean.getVideo_url());
                    note.setFileId(resultBean.getVideo_id());
                    note.setFileName(resultBean.getTitle());
                    note.setCompleteType("1");
                    note.setDuration(Integer.parseInt(resultBean.getDuration()));
                    downloadInfoDao.insert(note);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        downLoadFile(i, resultBean.getVideo_url(), resultBean.getVideo_id());
                    } else {
                        Toast.makeText(LiveRoomNewActivity.this, "手机版本过低，不支持下载", Toast.LENGTH_SHORT).show();
                    }
                    resultBean.setType(1);
                    listViewDownAdapter.notifyDataSetChanged();
                }
            }
        } else if (i == R.id.down_manage) {
            Intent intent = new Intent(this, LocalVideoActivity.class);
            startActivity(intent);
        } else if (i == R.id.change_size_img) {
            change_size_layout.setVisibility(View.VISIBLE);
        } else if (i == R.id.change_size_img1) {
            change_size_layout.setVisibility(View.GONE);
            setPlaySpeed(1.0f);
        } else if (i == R.id.change_size_img2) {
            change_size_layout.setVisibility(View.GONE);
            setPlaySpeed(1.25f);
        } else if (i == R.id.change_size_img3) {
            change_size_layout.setVisibility(View.GONE);
            setPlaySpeed(1.5f);
        } else if (i == R.id.change_size_img4) {
            change_size_layout.setVisibility(View.GONE);
            setPlaySpeed(2.0f);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == FULL_SCREEN_LIVE_VIDEO_BACK) {
            loadingView.setVisibility(View.VISIBLE);
            fullScreenImage.setVisibility(View.GONE);
            playCurrent = data.getIntExtra("Current", 0);
        }
    }

    private void setPlaySpeed(float speed) {
        if (mediaPlayer != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(speed));
                } else {
                    mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(speed));
                    mediaPlayer.pause();
                }
            } else {
                Toast.makeText(LiveRoomNewActivity.this, "您的手机版本过低，无法倍数播放", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(LiveRoomNewActivity.this, "视频加载中，请稍后再试", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressLint("UseSparseArrays")
    private void initView() {
        //用于显示上行视频的surfaceview
        videoLayout = findViewById(R.id.video_layout);
        back_img = findViewById(R.id.back_img);
        share_img = findViewById(R.id.share_img);
        down_video_img = findViewById(R.id.down_video_img);
        full_screen_img = findViewById(R.id.full_screen_img);
        change_size_img = findViewById(R.id.change_size_img);
        change_size_layout = findViewById(R.id.change_size_layout);
        change_size_img1 = findViewById(R.id.change_size_img1);
        change_size_img2 = findViewById(R.id.change_size_img2);
        change_size_img3 = findViewById(R.id.change_size_img3);
        change_size_img4 = findViewById(R.id.change_size_img4);

        back_img.setOnClickListener(this);
        share_img.setOnClickListener(this);
        down_video_img.setOnClickListener(this);
        full_screen_img.setOnClickListener(this);
        change_size_img.setOnClickListener(this);
        change_size_img1.setOnClickListener(this);
        change_size_img2.setOnClickListener(this);
        change_size_img3.setOnClickListener(this);
        change_size_img4.setOnClickListener(this);

        recorderLayout = findViewById(R.id.activity_join_code_video);
        liveRoomLayout = findViewById(R.id.live_room_layout);
        liveRoomContent = findViewById(R.id.live_room_content);
        liveRoomContentLayout = findViewById(R.id.live_room_content_layout);

        videoController = findViewById(R.id.videocontroller);

        RelativeLayout.LayoutParams recorderLayoutLayoutParams = (RelativeLayout.LayoutParams) videoLayout.getLayoutParams();

        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            //横屏
            recorderLayoutLayoutParams.height = CommonUtils.getScreenHeight(LiveRoomNewActivity.this);
            recorderLayoutLayoutParams.width = CommonUtils.getScreenWidth(LiveRoomNewActivity.this);

//            onLandscapeChanged();
        } else {
            recorderLayoutLayoutParams.height = CommonUtils.getScreenHeight(LiveRoomNewActivity.this) / 3;
            recorderLayoutLayoutParams.width = CommonUtils.getScreenWidth(LiveRoomNewActivity.this);
            //竖屏
            ViewGroup.LayoutParams liveRoomLayoutParams = liveRoomLayout.getLayoutParams();
            liveRoomLayoutParams.height = CommonUtils.getScreenHeight(this) * 2 / 3;
            liveRoomLayout.setLayoutParams(liveRoomLayoutParams);

            videoController.setLayoutParams(recorderLayoutLayoutParams);
//            onPortraitChanged();
        }
        videoLayout.setLayoutParams(recorderLayoutLayoutParams);

        layout1 = findViewById(R.id.layout1);
        LinearLayout layout2 = findViewById(R.id.layout2);
        LinearLayout layout3 = findViewById(R.id.layout3);
        text1 = findViewById(R.id.text1);
        text2 = findViewById(R.id.text2);
        text3 = findViewById(R.id.text3);
        view1 = findViewById(R.id.view1);
        view2 = findViewById(R.id.view2);
        view3 = findViewById(R.id.view3);
        layout_bottom = findViewById(R.id.layout_bottom);
        layout_bottom1 = findViewById(R.id.layout_bottom1);
        layout_bottom2 = findViewById(R.id.layout_bottom2);
        layout_bottom3 = findViewById(R.id.layout_bottom3);
        down_layout = findViewById(R.id.down_layout);
        TextView down_all_text = findViewById(R.id.down_all_text);
        TextView down_manage = findViewById(R.id.down_manage);
        down_all_text.setOnClickListener(this);
        down_manage.setOnClickListener(this);
        item_title = findViewById(R.id.item_title);
        close_down = findViewById(R.id.close_down);
        close_down.setOnClickListener(this);
        item_title.setText(getIntent().getStringExtra("item_title"));

        listview1 = findViewById(R.id.listview1);
        listview2 = findViewById(R.id.listview2);
        ListView listview3 = findViewById(R.id.listview3);
        down_listview = findViewById(R.id.down_listview);

        pptImgList = new ArrayList<>();
        listView3Adapter = new ListView3Adapter(this, pptImgList);
        listview3.setAdapter(listView3Adapter);

        resultBeanList = new ArrayList<>();
        listViewDownAdapter = new ListViewDownAdapter(LiveRoomNewActivity.this, resultBeanList);
        down_listview.setAdapter(listViewDownAdapter);
        down_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (resultBeanList.get(i).getType() == 0) {
                    Toast.makeText(LiveRoomNewActivity.this, "开始下载", Toast.LENGTH_SHORT).show();

                    DownloadInfo note = new DownloadInfo();
                    note.setUrl(resultBeanList.get(i).getVideo_url());
                    note.setFileId(resultBeanList.get(i).getVideo_id());
                    note.setFileName(resultBeanList.get(i).getTitle());
                    if (!CommonUtils.isEmpty(resultBeanList.get(i).getDuration())) {
                        note.setDuration(Integer.parseInt(resultBeanList.get(i).getDuration()));
                    } else {
                        note.setDuration(0);
                    }
                    note.setCompleteType("1");
                    downloadInfoDao.insert(note);
                    downLoadFile(i, resultBeanList.get(i).getVideo_url(), resultBeanList.get(i).getVideo_id());

                    resultBeanList.get(i).setType(1);
                    listViewDownAdapter.notifyDataSetChanged();
                } else if (resultBeanList.get(i).getType() == 1) {
                    Toast.makeText(LiveRoomNewActivity.this, "该课程正在下载中", Toast.LENGTH_SHORT).show();
                } else if (resultBeanList.get(i).getType() == 2) {
                    Toast.makeText(LiveRoomNewActivity.this, "该课程下载已完成", Toast.LENGTH_SHORT).show();
                }
            }
        });

        iMessageModelList = new ArrayList<>();
        listView1Adapter = new ListView1Adapter(this, iMessageModelList);
        listview1.setAdapter(listView1Adapter);

        listView2List = new ArrayList<>();
        playBackListBeanList = new ArrayList<>();
        playBackListMap = new HashMap<>();
        dataTreeList = new ArrayList<>();
        listview2.setLayoutManager(new LinearLayoutManager(this));
        listview2.setHasFixedSize(true);
        listview2.addItemDecoration(new RvDividerItemDecoration(this, LinearLayoutManager.VERTICAL));

        recyclerAdapter = new RecyclerAdapter(LiveRoomNewActivity.this);
        recyclerAdapter.setOnItemClickListener(new MyItemClick());
        recyclerAdapter.setOnGroupClickListener(new MyGroupClick());
        listview2.setAdapter(recyclerAdapter);

        listview3.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(LiveRoomNewActivity.this, ShowPPTActivity.class);
                intent.putStringArrayListExtra("ppt", (ArrayList<String>) pptImgList);
                intent.putExtra("position", position);
                startActivity(intent);

            }
        });

        etMessage = findViewById(R.id.activity_login_text_et);

        etMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_GO) {
                    CommonUtils.hindInputMethod(LiveRoomNewActivity.this, v);

                    String message = etMessage.getText().toString();
                    if (TextUtils.isEmpty(message)) {
                        return true;
                    }
                    // 发送聊天消息
                    liveRoom.getChatVM().sendMessage(message);
                    etMessage.setText("");
                    return true;
                }
                return false;
            }
        });

        layout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showView(1);
            }
        });
        layout2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showView(2);
            }
        });
        layout3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showView(3);
            }
        });

//        liveRoomContentLayout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (!CommonUtils.isEmpty(contentUrl)) {
//                    Intent intent = new Intent();
//                    intent.setData(Uri.parse(contentUrl));//Url 就是你要打开的网址
//                    intent.setAction(Intent.ACTION_VIEW);
//                    startActivity(intent); //启动浏览器
//                }
//            }
//        });
    }

    private void showView(int position) {
        text1.setTextColor(Color.parseColor("#FFBBBBBB"));
        text2.setTextColor(Color.parseColor("#FFBBBBBB"));
        text3.setTextColor(Color.parseColor("#FFBBBBBB"));
        view1.setVisibility(View.INVISIBLE);
        view2.setVisibility(View.INVISIBLE);
        view3.setVisibility(View.INVISIBLE);
        layout_bottom1.setVisibility(View.GONE);
        layout_bottom2.setVisibility(View.GONE);
        layout_bottom3.setVisibility(View.GONE);
        switch (position) {
            case 1:
                text1.setTextColor(Color.parseColor("#FF000000"));
                view1.setVisibility(View.VISIBLE);
                layout_bottom1.setVisibility(View.VISIBLE);
                break;
            case 2:
                text2.setTextColor(Color.parseColor("#FF000000"));
                view2.setVisibility(View.VISIBLE);
                layout_bottom2.setVisibility(View.VISIBLE);
                break;
            case 3:
                text3.setTextColor(Color.parseColor("#FF000000"));
                view3.setVisibility(View.VISIBLE);
                layout_bottom3.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    /**
     * 获取直播签名
     */
    private void getSign(final String roomId) {
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("token", getIntent().getStringExtra("token"));
        formBody.add("room_id", roomId);
        formBody.add("app", getIntent().getStringExtra("app"));
        formBody.add("major_type", getIntent().getStringExtra("major_type"));
        Request request = new Request.Builder()//创建Request 对象。
                .url(getIntent().getStringExtra("urlTitle") + "/api.php?c=Baijia&a=sign")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                cancelProgressDialog();
                LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LiveRoomNewActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
                    }
                });
                setFinish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                String responseStr = response.body().string();
                System.out.println("getSign==:" + responseStr);
                Gson gson = new Gson();
                SignBean signBean = gson.fromJson(responseStr, SignBean.class);
                if (signBean.getCode().equals("200")) {
                    enterRoom(roomId, signBean.getResult().getUser().getId(), signBean.getResult().getUser().getNickname()
                            , signBean.getResult().getUser().getAvatar(), signBean.getResult().getSign());
                }
            }
        });
    }

    private void enterRoom(String roomId, final String userNumber, String userName, String userAvatar, String sign) {
        LPConstants.LPUserType lpUserType = LPConstants.LPUserType.Student;
//        switch (getIntent().getIntExtra("lpUserType", 0)) {
//            case 0:
//                lpUserType = LPConstants.LPUserType.Student;
//                break;
//            case 1:
//                lpUserType = LPConstants.LPUserType.Teacher;
//                break;
//            case 2:
//                lpUserType = LPConstants.LPUserType.Assistant;
//                break;
//            case 3:
//                lpUserType = LPConstants.LPUserType.Visitor;
//                break;
//            default:
//                lpUserType = LPConstants.LPUserType.Visitor;
//                break;
//        }

        liveRoom = LiveSDK.enterRoom(this, Long.parseLong(roomId), userNumber, userName,
                lpUserType, userAvatar, sign, new LPLaunchListener() {
                    //        liveRoom = LiveSDK.enterRoom(context, code, name, new LPLaunchListener() {
                    @Override
                    public void onLaunchSteps(int step, int totalStep) {
                        Log.i("init steps", "step:" + step + "/" + totalStep);
                    }

                    @Override
                    public void onLaunchError(LPError error) {
                        cancelProgressDialog();
                        Log.e("error", error.getCode() + " " + error.getMessage());
                        Toast.makeText(LiveRoomNewActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                        setFinish();
                    }

                    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                    @Override
                    public void onLaunchSuccess(LiveRoom liveRoom) {
                        System.out.println("进如房间成功");
                        layout1.setVisibility(View.VISIBLE);
                        showView(1);
                        recorderLayout.setVisibility(View.VISIBLE);
                        change_size_img.setVisibility(View.GONE);
                        videoController.setVisibility(View.GONE);
                        down_video_img.setVisibility(View.GONE);
                        full_screen_img.setVisibility(View.VISIBLE);

                        userId = userNumber;
                        onInitSuccess(liveRoom);

                        cancelProgressDialog();
                    }
                });

    }

    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void onInitSuccess(LiveRoom mLiveRoom) {
        CommonUtils.keepScreenOn(wakeLock, this, true);
        CommonUtils.keepScreenLongLight(this, true);
        this.liveRoom = mLiveRoom;
        textureView = ViETextureViewRenderer.CreateRenderer(LiveRoomNewActivity.this, true);
        recorderLayout.addView(textureView);
        recorder = liveRoom.getRecorder();

        player = liveRoom.getPlayer();
//        player.playVideo(userId, textureView);   //播放音视频

//        LPPlayer player = liveRoom.getPlayer();
        player.playAudio(userId);   //播放音频
//        player.playAVClose(userId); //关闭音视频流

        System.out.println("getSpeakQueueVM==getSpeakQueueList" + liveRoom.getSpeakQueueVM().getSpeakQueueList().size());
        System.out.println("getSpeakQueueVM==getApplyList" + liveRoom.getSpeakQueueVM().getApplyList().size());

        for (IMediaModel iUserModel : liveRoom.getSpeakQueueVM().getSpeakQueueList()) {
            System.out.println("iUserModel==getUserId" + iUserModel.getUser().getUserId());
            System.out.println("iUserModel==getAvatar" + iUserModel.getUser().getAvatar());
            System.out.println("iUserModel==getName" + iUserModel.getUser().getName());
            System.out.println("iUserModel==getType" + iUserModel.getUser().getType());
        }

        // 老师远程控制
//        liveRoom.getSpeakQueueVM().getObservableOfActiveUsers().observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new rx.Observer<List<IMediaModel>>() {
//                    @Override
//                    public void onCompleted() {
//                        System.out.println("onCompleted");
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        System.out.println("onError");
//                    }
//
//                    @Override
//                    public void onNext(List<IMediaModel> iMediaModels) {
//                        System.out.println("onNext");
//                        for (IMediaModel iMediaModel:iMediaModels){
//                            System.out.println(iMediaModel.getUser().getUserId());
//                        }
//                    }
//                });
//        liveRoom.getSpeakQueueVM().requestActiveUsers();

        LPPPTFragment lppptFragment = new LPPPTFragment();
        lppptFragment.setLiveRoom(liveRoom);
        final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.activity_join_code_video, lppptFragment);
        transaction.commitAllowingStateLoss();
        lppptFragment.setFlingEnable(true);

        // 收到聊天消息
        liveRoom.getChatVM().getObservableOfReceiveMessage().subscribe(new Action1<IMessageModel>() {
            @Override
            public void call(IMessageModel iMessageModel) {
                System.out.println("收到聊天消息==:" + iMessageModel.getFrom().getAvatar());
                iMessageModelList.add(iMessageModel);
                listView1Adapter.notifyDataSetChanged();

//                listview1.setSelection(iMessageModelList.size() - 1);
                listview1.setSelection(listview1.getBottom());
//                refreshLogView(iMessageModel.getFrom().getName() + ":" + iMessageModel.getContent() + "\n");
            }
        });
        // 房间人数改变
        liveRoom.getObservableOfUserNumberChange().observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
//                refreshLogView("房间人数:" + integer + "\n");
            }
        });
        // 用户进入
        liveRoom.getObservableOfUserIn().observeOn(AndroidSchedulers.mainThread()).subscribe(new LPBackPressureBufferedSubscriber<IUserInModel>() {
            @Override
            public void call(IUserInModel iUserInModel) {
//                tvMessages.append("用户进入:" + iUserInModel.getUser().getName() + "\n");
            }
        });
        // 用户退出
        liveRoom.getObservableOfUserOut().observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
            @Override
            public void call(String userId) {
//                tvMessages.append("用户退出:" + userId + "\n");
            }
        });
        // 全体禁言
        liveRoom.getObservableOfForbidAllChatStatus().observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
//                        btnSend.setEnabled(!aBoolean);
                    }
                });
        // 登录冲突
        liveRoom.getObservableOfLoginConflict().observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ILoginConflictModel>() {
                    @Override
                    public void call(ILoginConflictModel iLoginConflictModel) {
//                        Toast.makeText(LiveRoomActivity.this, "您的账号在" + iLoginConflictModel.getConflictEndType().name() + "端登录",
//                                Toast.LENGTH_SHORT).show();
//                        setFinish();
                    }
                });
        // 用户列表回调
        liveRoom.getOnlineUserVM().getObservableOfOnlineUser().observeOn(AndroidSchedulers.mainThread())
                .subscribe(new LPErrorPrintSubscriber<List<IUserModel>>() {
                    @Override
                    public void call(List<IUserModel> iUserModels) {
//                        tvMessages.append("users:");
                        for (IUserModel model : iUserModels)
                            System.out.println(model.getName() + "--" + model.getUserId());
                    }
                });
        // 公告修改通知
        liveRoom.getObservableOfAnnouncementChange().observeOn(AndroidSchedulers.mainThread())
                .subscribe(new LPErrorPrintSubscriber<IAnnouncementModel>() {
                    @Override
                    public void call(IAnnouncementModel iAnnouncementModel) {
                        content = iAnnouncementModel.getContent();
                        contentUrl = iAnnouncementModel.getLink();

                        System.out.println("公告修改通知:" + iAnnouncementModel.getContent());
                        System.out.println("公告修改通知:" + iAnnouncementModel.getLink());
//                        liveRoomContent.setText(content);
//                        tvMessages.append(iAnnouncementModel.getContent());
//                        tvMessages.append("\n");
                    }
                });

        // 主动请求公告
        liveRoom.requestAnnouncement();

        // 监听上课
        liveRoom.getObservableOfClassStart().subscribe(new LPErrorPrintSubscriber<Void>() {
            @Override
            public void call(Void aVoid) {
//                tvMessages.append("上课了\n");
            }
        });
        liveRoom.getObservableOfClassEnd().subscribe(new LPErrorPrintSubscriber<Void>() {
            @Override
            public void call(Void aVoid) {
//                tvMessages.append("下课了\n");
            }
        });
        // 上行链路切换
        recorder.getObservableOfLinkType().subscribe(new LPErrorPrintSubscriber<LPConstants.LPLinkType>() {
            @Override
            public void call(LPConstants.LPLinkType lpLinkType) {
//                tvMessages.append("上行:" + lpLinkType.name() + "\n");
            }
        });
        // 下行链路切换
        player.getObservableOfLinkType().subscribe(new LPErrorPrintSubscriber<LPConstants.LPLinkType>() {
            @Override
            public void call(LPConstants.LPLinkType lpLinkType) {
//                tvMessages.append("下行:" + lpLinkType.name() + "\n");
            }
        });
        // error 回调
        liveRoom.setOnLiveRoomListener(new OnLiveRoomListener() {
            @Override
            public void onError(LPError lpError) {
                Log.e("error", lpError.getMessage());
//                tvMessages.append("error code:" + lpError.getCode() + " error msg:" + lpError.getMessage() + "\n");
            }
        });

        // 老师远程控制
        liveRoom.getSpeakQueueVM().getObservableOfMediaControl().observeOn(AndroidSchedulers.mainThread())
                .subscribe(new LPErrorPrintSubscriber<IMediaControlModel>() {
                    @Override
                    public void call(IMediaControlModel iMediaControlModel) {
//                        if (!iMediaControlModel.isApplyAgreed()) {
                        // 老师关闭发言
//                            isSpeakingAllowed = false;
//                            videoItemState = false;
//                            audioItemState = false;
//                            beautyFilterState = false;
//                            captureVideoDefinition = false;
//                        }
                    }
                });

        //上课
        if (liveRoom.getCurrentUser().getType() == LPConstants.LPUserType.Teacher)
            liveRoom.requestClassStart();

        // 点名
        liveRoom.setOnRollCallListener(new OnPhoneRollCallListener() {
            @Override
            public void onRollCall(int time, final RollCall rollCallListener) {
                dialog = new AlertDialog.Builder(LiveRoomNewActivity.this).setTitle("点名了")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                rollCallListener.call();
                            }
                        }).create();
                dialog.show();
            }

            @Override
            public void onRollCallTimeOut() {
                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();
            }
        });


        //-----------------------------------------
        playerVideoModel = new ArrayList<>();

        Subscriber<List<IMediaModel>> subs = new LPErrorPrintSubscriber<List<IMediaModel>>() {
            @Override
            public void call(List<IMediaModel> iMediaModels) {
                playerVideoModel.clear();
                if (iMediaModels != null) {
                    for (IMediaModel model : iMediaModels) {
                        if (model.isVideoOn()) {
                            playerVideoModel.add(model);
                        }
                    }

                    for (IMediaModel iMediaModel : playerVideoModel) {
                        System.out.println("getUserId==3==" + iMediaModel.getUser().getUserId());
                    }

                }
            }
        };
        // 进入房间首次获取发言队列
        Observable<List<IMediaModel>> obs = liveRoom.getSpeakQueueVM().getObservableOfActiveUsers();
        obs.subscribe(subs);
        liveRoom.getSpeakQueueVM().requestActiveUsers();
        // 发言人音视频状态改变
        liveRoom.getSpeakQueueVM().getObservableOfMediaChange().observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IMediaModel>() {
                    @Override
                    public void call(IMediaModel iMediaModel) {
                        String userId = iMediaModel.getUser().getUserId();
                        IMediaModel model = getVideoMediaById(userId);
                        System.out.println("media change:" + iMediaModel.getUser().getName() + "\n");
                        if (iMediaModel.isVideoOn() && !playerVideoModel.contains(model)) {
                            playerVideoModel.add(iMediaModel);
                        } else if (!iMediaModel.isVideoOn()) {
                            playerVideoModel.remove(model);
//                            if (userId.equals(currentPlayingVideoUserId)) {
//                                currentPlayingVideoUserId = null;
//                            }
                        }

                        for (IMediaModel iMediaModel1 : playerVideoModel) {
                            System.out.println("getUserId==2==" + iMediaModel1.getUser().getUserId());
                        }

                    }
                });
        // 新的发言
        liveRoom.getSpeakQueueVM().getObservableOfMediaNew().observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IMediaModel>() {
                    @Override
                    public void call(IMediaModel iMediaModel) {
                        System.out.println("media new:" + iMediaModel.getUser().getName() + "\n");
                        if (iMediaModel.isVideoOn()) {
                            playerVideoModel.add(iMediaModel);

                            for (IMediaModel iMediaModel1 : playerVideoModel) {
                                System.out.println("getUserId==1==" + iMediaModel1.getUser().getUserId());
                            }
                        }
                    }
                });
//        player.playAudio(currentPlayingVideoUserId);
    }

    List<IMediaModel> playerVideoModel;

    private IMediaModel getVideoMediaById(String userId) {
        for (IMediaModel model : playerVideoModel) {
            if (model.getUser().getUserId().equals(userId))
                return model;
        }
        return null;
    }

    //课程id为new=1  getLiveRoom  getPlayback  getPlaybackSlice
    //课程id为new=0    getNodes_new

    /**
     * 获取直播课时列表
     */
    private void getLiveRoomApp() {
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("token", getIntent().getStringExtra("token"));
        formBody.add("app", getIntent().getStringExtra("app"));
        formBody.add("major_type", getIntent().getStringExtra("major_type"));
        formBody.add("course_id", getIntent().getStringExtra("course_id"));
        Request request = new Request.Builder()//创建Request 对象。
//                .url("https://api.laoyaojing.net/api.php?c=live&a=getLiveRoom")
                .url(getIntent().getStringExtra("urlTitle") + "/api.php?c=live&a=getLiveRoomApp")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                cancelProgressDialog();
                LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LiveRoomNewActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
                    }
                });
                setFinish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                cancelProgressDialog();
                assert response.body() != null;
                String responseStr = response.body().string();
                System.out.println("getLiveRoomApp==:" + responseStr);
                Gson gson = new Gson();
                GetLiveRoomAppBean classListBean = gson.fromJson(responseStr, GetLiveRoomAppBean.class);
                if (classListBean.getCode().equals("200")) {
                    List<GetLiveRoomAppBean.ResultBean.ListBean> beanXList = classListBean.getResult().getList();

                    cancelProgressDialog();
                    for (int i = 0; i < beanXList.size(); i++) {
                        PlayBackListBean mainPlayBackListBean = new PlayBackListBean();
                        mainPlayBackListBean.setType(0);
                        mainPlayBackListBean.setId(beanXList.get(i).getId());
                        mainPlayBackListBean.setTitle(beanXList.get(i).getTitle());
                        mainPlayBackListBean.setStart_time(beanXList.get(i).getStart_time());
                        mainPlayBackListBean.setCourse_id(beanXList.get(i).getCourse_id());
                        mainPlayBackListBean.setVideoid(beanXList.get(i).getVideo_id());
                        mainPlayBackListBean.setEnd_time(beanXList.get(i).getEnd_time());
                        mainPlayBackListBean.setDuration(beanXList.get(i).getDuration());
                        mainPlayBackListBean.setFree(beanXList.get(i).getFree());
                        mainPlayBackListBean.setRoom_id(beanXList.get(i).getRoom_id());
                        mainPlayBackListBean.setOpen_applet_camera(beanXList.get(i).getOpen_applet_camera());
                        mainPlayBackListBean.setYear(beanXList.get(i).getYear());
                        mainPlayBackListBean.setStart_time2(beanXList.get(i).getStart_time2());
                        mainPlayBackListBean.setEnd_time2(beanXList.get(i).getEnd_time2());
                        mainPlayBackListBean.setIs_live(beanXList.get(i).getIs_live());

                        for (PlayBackListBean playBackListBean : beanXList.get(i).getPlayback()) {
                            playBackListBean.setType(3);
                        }
                        for (PlayBackListBean playBackListBean : beanXList.get(i).getChildren()) {
                            playBackListBean.setType(4);
                        }
                        List<PlayBackListBean> playBackListBeanList = new ArrayList<>();
                        playBackListBeanList.add(mainPlayBackListBean);
                        playBackListBeanList.addAll(beanXList.get(i).getPlayback());
                        playBackListBeanList.addAll(beanXList.get(i).getChildren());

                        playBackListMap.put(i, playBackListBeanList);
                        dataTreeList.add(new SecondaryListAdapter.DataTree<>(CommonUtils.numberToChinese(i + 1) + "."
                                + beanXList.get(i).getTitle(),
                                playBackListBeanList));
                    }
                    LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            recyclerAdapter.setData(dataTreeList);

                            checkPrivilegeIsFree(((PlayBackListBean) dataTreeList.get(0).getSubItems().get(0)).getId());

                            if (getIntent().getStringExtra("is_live").equals("3")) {
                                for (Map.Entry<Integer, List<PlayBackListBean>> me : playBackListMap.entrySet()) {
                                    // 根据键值对对象获取键和值
                                    List<PlayBackListBean> value = me.getValue();
                                    for (PlayBackListBean playBackListBean1 : value) {
                                        if (playBackListBean1.getType() == 0 && playBackListBean1.getIs_live() == 3) {
                                            getSign(playBackListBean1.getRoom_id());
                                        }
                                    }
                                }
                            }

                        }
                    });

//                    if (!beanXList.isEmpty() && getIntent().getStringExtra("is_live").equals("3")) {
//                        //进入房间
//                        getSign(beanXList.get(0).getRoom_id());
//                    } else {
//                        cancelProgressDialog();
//                        for (int i = 0; i < beanXList.size(); i++) {
//                            for (PlayBackListBean playBackListBean : beanXList.get(i).getPlayback()) {
//                                playBackListBean.setType(3);
//                            }
//                            for (PlayBackListBean playBackListBean : beanXList.get(i).getChildren()) {
//                                playBackListBean.setType(4);
//                            }
//                            List<PlayBackListBean> playBackListBeanList = new ArrayList<>();
//                            playBackListBeanList.addAll(beanXList.get(i).getPlayback());
//                            playBackListBeanList.addAll(beanXList.get(i).getChildren());
//
//                            playBackListMap.put(i, playBackListBeanList);
//                            dataTreeList.add(new SecondaryListAdapter.DataTree<>(CommonUtils.numberToChinese(i + 1) + "."
//                                    + beanXList.get(i).getTitle(),
//                                    playBackListBeanList));
//                        }
//                        LiveRoomActivity.this.runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                recyclerAdapter.setData(dataTreeList);
//                                if (!dataTreeList.isEmpty() && !dataTreeList.get(0).getSubItems().isEmpty())
//                                    playVideo((PlayBackListBean) dataTreeList.get(0).getSubItems().get(0));
//                            }
//                        });
//                    }
                }
            }
        });
    }

//
//    /**
//     * 获取直播课时列表2
//     */
//    private void getClassList() {
//        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
//        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
//        formBody.add("token", getIntent().getStringExtra("token"));
//        formBody.add("app", getIntent().getStringExtra("app"));
//        formBody.add("major_type", getIntent().getStringExtra("major_type"));
//        formBody.add("course_id", getIntent().getStringExtra("course_id"));
//        formBody.add("down", "desc");
//        Request request = new Request.Builder()//创建Request 对象。
////                .url("https://api.laoyaojing.net/api.php?c=live&a=getLiveRoom")
//                .url(getIntent().getStringExtra("urlTitle") + "/api.php?c=live&a=getLiveRoom")
//                .post(formBody.build())//传递请求体
//                .build();
//        client.newCall(request).enqueue(new Callback() {
//
//            @Override
//            public void onFailure(Call call, IOException e) {
//                cancelProgressDialog();
//                LiveRoomActivity.this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(LiveRoomActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
//                    }
//                });
//                setFinish();
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                assert response.body() != null;
//                String responseStr = response.body().string();
//                System.out.println("getLiveRoom==:" + responseStr);
//                Gson gson = new Gson();
//                ClassListBean classListBean = gson.fromJson(responseStr, ClassListBean.class);
//                if (classListBean.getCode().equals("200")) {
//                    listView2List.addAll(classListBean.getResult().getList());
//                    getSecondDate(datePosition);
////                    getPlayback(datePosition, listView2List.get(datePosition).getId());
//                }
//            }
//        });
//    }
//
//    private void getSecondDate(int position) {
//        getPlayback(position, listView2List.get(position).getId());
//    }
//
//    private void getPlayback(final int position, final String liveId) {
//        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
//        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
//        formBody.add("token", getIntent().getStringExtra("token"));
//        formBody.add("app", getIntent().getStringExtra("app"));
//        formBody.add("major_type", getIntent().getStringExtra("major_type"));
//        formBody.add("live_id", liveId);
//        formBody.add("down", "desc");
//        Request request = new Request.Builder()//创建Request 对象。
//                .url(getIntent().getStringExtra("urlTitle") + "/api.php?c=live&a=getPlayback")
//                .post(formBody.build())//传递请求体
//                .build();
//        client.newCall(request).enqueue(new Callback() {
//
//            @Override
//            public void onFailure(Call call, IOException e) {
//                cancelProgressDialog();
//                LiveRoomActivity.this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(LiveRoomActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
//                    }
//                });
//                setFinish();
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                assert response.body() != null;
//                String responseStr = response.body().string();
//                System.out.println("getPlayback==:" + responseStr);
//                Gson gson = new Gson();
//                PlayBackBean playBackBean = gson.fromJson(responseStr, PlayBackBean.class);
//                if (playBackBean.getCode().equals("200")) {
//                    for (PlayBackListBean playBackListBean : playBackBean.getResult().getList()) {
//                        playBackListBean.setType(0);
//                    }
//                    playBackListBeanList.addAll(playBackBean.getResult().getList());
//                    getPlaybackSlice(position, liveId);
//                }
//            }
//        });
//    }
//
//    /**
//     * 获取直播回放切片2
//     *
//     * @param position
//     * @param liveId
//     */
//    private void getPlaybackSlice(final int position, String liveId) {
//        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
//        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
//        formBody.add("token", getIntent().getStringExtra("token"));
//        formBody.add("app", getIntent().getStringExtra("app"));
//        formBody.add("major_type", getIntent().getStringExtra("major_type"));
//        formBody.add("live_id", liveId);
//        Request request = new Request.Builder()//创建Request 对象。
//                .url(getIntent().getStringExtra("urlTitle") + "/api.php?c=live&a=getPlaybackSlice2")
//                .post(formBody.build())//传递请求体
//                .build();
//        client.newCall(request).enqueue(new Callback() {
//
//            @Override
//            public void onFailure(Call call, IOException e) {
//                cancelProgressDialog();
//                LiveRoomActivity.this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(LiveRoomActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
//                    }
//                });
//                setFinish();
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                assert response.body() != null;
//                String responseStr = response.body().string();
//                System.out.println("getPlaybackSlice2==:" + responseStr);
//                Gson gson = new Gson();
//                PlayBackSlice playBackSlice = gson.fromJson(responseStr, PlayBackSlice.class);
//                if (playBackSlice.getCode().equals("200")) {
//                    for (PlayBackListBean playBackListBean : playBackSlice.getResult().getList()) {
//                        playBackListBean.setType(1);
//                    }
//                    playBackListBeanList.addAll(playBackSlice.getResult().getList());
//                    playBackListMap.put(datePosition, playBackListBeanList);
//                    dataTreeList.add(new SecondaryListAdapter.DataTree<>(listView2List.get(datePosition).getTitle(), playBackListBeanList));
//                    datePosition++;
//                    if (listView2List.size() - 1 > position) {
//                        playBackListBeanList.clear();
//                        getSecondDate(datePosition);
//                    } else {
//                        LiveRoomActivity.this.runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                recyclerAdapter.setData(dataTreeList);
//                                if (!dataTreeList.isEmpty() && !dataTreeList.get(0).getSubItems().isEmpty())
//                                    playVideo((PlayBackListBean) dataTreeList.get(0).getSubItems().get(0));
//                            }
//                        });
//                        cancelProgressDialog();
//                    }
//                }
//            }
//        });
//    }

    /**
     * 获取录播课时列表
     */
    private void getNodes() {
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("token", getIntent().getStringExtra("token"));
        formBody.add("app", getIntent().getStringExtra("app"));
        formBody.add("major_type", getIntent().getStringExtra("major_type"));
        formBody.add("id", getIntent().getStringExtra("course_id"));
        Request request = new Request.Builder()//创建Request 对象。
                .url(getIntent().getStringExtra("urlTitle") + "/api.php?c=Course&a=getNodes_new")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                cancelProgressDialog();
                LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LiveRoomNewActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
                    }
                });
                setFinish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                cancelProgressDialog();
                assert response.body() != null;
                String responseStr = response.body().string();
                System.out.println("getNodes_new=response=:" + responseStr);
                Gson gson = new Gson();
                GetNodesBean getNodesBean = gson.fromJson(responseStr, GetNodesBean.class);
                if (getNodesBean.getCode() == 200) {
                    List<GetNodesBean.ResultBean.ListBeanX> beanXList = getNodesBean.getResult().getList();
                    for (int i = 0; i < beanXList.size(); i++) {
                        for (PlayBackListBean playBackListBean : getNodesBean.getResult().getList().get(i).getList()) {
                            playBackListBean.setType(2);
                        }
                        playBackListMap.put(i, getNodesBean.getResult().getList().get(i).getList());
                        dataTreeList.add(new SecondaryListAdapter.DataTree<>(CommonUtils.numberToChinese(i + 1) + "." + getNodesBean.getResult().getList().get(i).getTitle(),
                                getNodesBean.getResult().getList().get(i).getList()));
                    }
                    LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            recyclerAdapter.setData(dataTreeList);
//                            if (!dataTreeList.isEmpty() && !dataTreeList.get(0).getSubItems().isEmpty())
//                                playVideo((PlayBackListBean) dataTreeList.get(0).getSubItems().get(0));

                            if (dataTreeList != null && !dataTreeList.isEmpty()) {
                                checkPrivilegeIsFree(((PlayBackListBean) dataTreeList.get(0).getSubItems().get(0)).getId());
                            }
                        }
                    });
                }
            }
        });
    }

    /**
     * 获取录播ppt
     *
     * @param id
     * @param showLoad
     */
    private void getIntro(String id, final boolean showLoad) {
        if (showLoad)
            buildProgressDialog(false);

        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("token", getIntent().getStringExtra("token"));
        formBody.add("app", getIntent().getStringExtra("app"));
        formBody.add("major_type", getIntent().getStringExtra("major_type"));
        formBody.add("id", id);
        Request request = new Request.Builder()//创建Request 对象。
                .url(getIntent().getStringExtra("urlTitle") + "/api.php?c=Course&a=getIntro")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                cancelProgressDialog();
                LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LiveRoomNewActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
                    }
                });
                setFinish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                cancelProgressDialog();
                assert response.body() != null;
                String responseStr = response.body().string();
                System.out.println("getIntro==:" + responseStr);
                Gson gson = new Gson();
                final IntroBean introBean = gson.fromJson(responseStr, IntroBean.class);
                if (introBean.getCode() == 200) {
                    LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pptImgList.clear();
                            pptImgList.addAll(introBean.getResult().getImages());
                            listView3Adapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        });
    }

    /**
     * 获取下载视频列表
     */
    private void getRalationDownloads() {
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("token", getIntent().getStringExtra("token"));
//        formBody.add("token", "b83146c5f532be624674976e8f61ce95");
        formBody.add("course_id", getIntent().getStringExtra("course_id"));
        Request request = new Request.Builder()//创建Request 对象。
//                .url("https://api.laoyaojing.net/api.php?c=live&a=getLiveRoom")
                .url(getIntent().getStringExtra("urlTitle") + "/Course/getRalationDownloads")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                cancelProgressDialog();
                LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LiveRoomNewActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
                    }
                });
                setFinish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                cancelProgressDialog();
                assert response.body() != null;
                String responseStr = response.body().string();
                System.out.println("getRalationDownloads==:" + responseStr);
                Gson gson = new Gson();
                final RalationDownloads classListBean = gson.fromJson(responseStr, RalationDownloads.class);
                if (classListBean.getCode().equals("200")) {
                    LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            resultBeanList.clear();
                            for (RalationDownloads.ResultBean resultBean : classListBean.getResult()) {
                                if (!CommonUtils.isEmpty(resultBean.getVideo_url())) {
                                    resultBeanList.add(resultBean);
                                }
                            }

                            for (RalationDownloads.ResultBean resultBean : resultBeanList) {
                                if (!CommonUtils.isEmpty(resultBean.getVideo_url())) {
                                    List<DownloadInfo> downloadInfoList =
                                            downloadInfoDao.queryBuilder()
                                                    .where(DownloadInfoDao.Properties.Url.eq(resultBean.getVideo_url())).list();
                                    if (!downloadInfoList.isEmpty()) {
                                        if (downloadInfoList.get(0).getCompleteType() == null) {
                                            resultBean.setType(0);
                                        } else if (downloadInfoList.get(0).getCompleteType().equals("2")) {
                                            resultBean.setType(2);
                                        } else if (downloadInfoList.get(0).getCompleteType().equals("0")) {
                                            resultBean.setType(0);
                                        } else if (downloadInfoList.get(0).getCompleteType().equals("1")) {
                                            resultBean.setType(1);
                                        }
                                    }
                                }
                            }
                            listViewDownAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        });
    }

    /**
     * 获取视频地址
     */
    private void getVideoUrl(String videoId, final String title) {
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
//        formBody.add("token", getIntent().getStringExtra("token"));
        formBody.add("mediaid", videoId);
//        formBody.add("app", getIntent().getStringExtra("app"));
//        formBody.add("major_type", getIntent().getStringExtra("major_type"));
        Request request = new Request.Builder()//创建Request 对象。
//                .url("https://api.laoyaojing.net/api.php?c=live&a=getLiveRoom")
                .url(getIntent().getStringExtra("urlTitle") + "/api.php?c=Course&a=getAlimedia")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                cancelProgressDialog();
                LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LiveRoomNewActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
                    }
                });
                setFinish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                cancelProgressDialog();
                assert response.body() != null;
                String responseStr = response.body().string();
                System.out.println("getAlimedia==:" + responseStr);
                Gson gson = new Gson();
                final GetVideoUrl classListBean = gson.fromJson(responseStr, GetVideoUrl.class);
                if (classListBean.getCode().equals("200")) {
                    LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            videoPath = classListBean.getResult().getUrls().getMp4();
                            startCurVideoView();
                        }
                    });
                }
            }
        });
    }

    /**
     * 添加回放/录播进度
     */
    private void addPlaybackProgress(String playback_id, String progress, String duration, String type, String course_id) {
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("token", getIntent().getStringExtra("token"));
        formBody.add("playback_id", playback_id);
        formBody.add("progress", progress);
        formBody.add("duration", duration);
        formBody.add("type", type);
        formBody.add("course_id", course_id);
        Request request = new Request.Builder()//创建Request 对象。
//                .url("https://api.laoyaojing.net/api.php?c=live&a=getLiveRoom")
                .url(getIntent().getStringExtra("urlTitle") + "/api.php?c=live&a=addPlaybackProgress")
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                cancelProgressDialog();
                LiveRoomNewActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LiveRoomNewActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
                    }
                });
                setFinish();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                cancelProgressDialog();
                assert response.body() != null;
                String responseStr = response.body().string();
                System.out.println("addPlaybackProgress==:" + responseStr);

            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    private void playVideo(PlayBackListBean playBackListBean) {
        if (playNextVideo && !CommonUtils.isEmpty(playId)) {
            addPlaybackProgress(playId, (videoView.getCurrentPosition() / 1000) + "",
                    (videoView.getDuration() / 1000) + "",
                    "0", getIntent().getStringExtra("course_id"));
        }
        //点击视频
        String videoUrl;
//        if (playBackListBean.getType() == 0) {
//            videoUrl = playBackListBean.getVideo_url();
//        } else if (playBackListBean.getType() == 1) {
//            videoUrl = playBackListBean.getUrl();
//        } else
        System.out.println("getType" + playBackListBean.getType());
        System.out.println("getAudio_url" + playBackListBean.getAudio_url());
        System.out.println("getUrl" + playBackListBean.getUrl());
        System.out.println("getVideoid" + playBackListBean.getVideoid());
        if (playBackListBean.getType() == 2) {
            buildProgressDialog(false);
            getVideoUrl(playBackListBean.getVideoid(), playBackListBean.getTitle());
//            videoUrl = playBackListBean.getAudio_url();
//            videoController.setUp(videoUrl, "", playBackListBean.getTitle());
//            videoController.playVideo();
        } else if (playBackListBean.getType() == 3) {
            videoUrl = playBackListBean.getVideo_url();
            videoPath = videoUrl;
            startCurVideoView();
        } else if (playBackListBean.getType() == 4) {
            buildProgressDialog(false);
            getVideoUrl(playBackListBean.getVideoid(), playBackListBean.getTitle());
        } else if (playBackListBean.getType() == 0) {
//            buildProgressDialog(false);
//            getVideoUrl(playBackListBean.getVideoid(), playBackListBean.getTitle());
        }

        playNextVideo = true;
        playId = playBackListBean.getId();
    }

    private class MyGroupClick implements RecyclerAdapter.OnGroupClickListener {

        @Override
        public void onGroupClickListener(int groupItemIndex) {
            List<PlayBackListBean> playBackListBeanList = playBackListMap.get(groupItemIndex);
            if (!hasPower || playBackListBeanList == null || playBackListBeanList.isEmpty()) {
                Toast.makeText(LiveRoomNewActivity.this, "没有权限", Toast.LENGTH_LONG).show();
            } else {
                System.out.println("groupItemIndex==" + groupItemIndex);

//                View view = linearLayoutManager.findViewByPosition(2);    //2为recyclerView中item位置，
//                ImageView item_play_title_img = (ImageView) view.findViewById(R.id.item_play_title_img);
//                item_play_title_img.setImageResource(R.mipmap.group_up);

//                View view = listview2.getChildAt(groupItemIndex);
//                ImageView item_play_title_img = (ImageView) view.findViewById(R.id.item_play_title_img);
//                item_play_title_img.setImageResource(R.mipmap.group_down);
//                item_play_title_img.setImageResource(R.mipmap.group_up);
            }
        }
    }

    private class MyItemClick implements RecyclerAdapter.OnItemClickListener {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onItemClickListener(int groupItemIndex, int subItemIndex) {
            if (!hasPower) {
                Toast.makeText(LiveRoomNewActivity.this, "没有权限", Toast.LENGTH_LONG).show();
            } else {
                PlayBackListBean playBackListBean = playBackListMap.get(groupItemIndex).get(subItemIndex);
                if (playBackListBean.getType() == 0 && playBackListBean.getIs_live() == 3) {
                    getSign(playBackListBean.getRoom_id());
                } else {
                    //点击视频
                    playVideo(playBackListBean);
                    recorderLayout.setVisibility(View.GONE);
                    videoController.setVisibility(View.VISIBLE);

                    //如果正在直播关闭直播
                    if (liveRoom != null) {
                        liveRoom.quitRoom();
                        liveRoom = null;
                    }
                }
            }

            //获取新的ppt
//            getIntro(playBackListBean.getId(), false);
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1000:
                    System.out.println("arg1:" + msg.arg1 + "");
                    if (resultBeanList != null && resultBeanList.size() > msg.arg2) {
                        System.out.println("resultBeanList.size()" + resultBeanList.size());
                        resultBeanList.get(msg.arg2).setProgress(msg.arg1 + "");
                        listViewDownAdapter.notifyDataSetChanged();
                    }
                    break;
                default:
                    break;
            }
        }
    };


    @RequiresApi(api = Build.VERSION_CODES.N)
    private void downLoadFile(final int position, String url, String fileName) {
        DownloadManager.getInstance().download(url, fileName, new DownLoadObserver() {
            @Override
            public void onNext(final DownloadInfo value) {
                super.onNext(value);
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Message message = new Message();
//                        message.what = 1000;
//                        message.arg1 = (int) ((double) value.getProgress() / (double) value.getTotal() * 100);
//                        message.arg2 = position;
//                        handler.sendMessage(message);
//                    }
//                }).start();
                System.out.println(value.getFileName() + "==:" + value.getTotal() + "----" + value.getProgress());
//                System.out.println(value.getFileName() + "==:" + (int) ((double) value.getProgress() / (double) value.getTotal() * 100));
            }

            @Override
            public void onComplete() {
                if (downloadInfo != null) {
                    List<DownloadInfo> downloadInfoList = downloadInfoDao.queryBuilder()
                            .where(DownloadInfoDao.Properties.Url.eq(downloadInfo.getUrl()))
                            .list();

                    if (downloadInfoList.isEmpty()) {
                        DownloadInfo note = new DownloadInfo();
                        note.setUrl(downloadInfo.getUrl());
                        note.setFileName(downloadInfo.getFileName());
                        note.setFileId(downloadInfo.getFileId());
                        note.setSavePath(downloadInfo.getSavePath());
                        note.setDuration(downloadInfo.getDuration());
                        note.setCompleteType("2");
                        note.setClassId(getIntent().getStringExtra("course_id"));
                        note.setClassName(getIntent().getStringExtra("item_title"));
                        downloadInfoDao.insert(note);
                    } else {
                        DownloadInfo loadInfo;
                        loadInfo = downloadInfoList.get(0);
                        loadInfo.setSavePath(downloadInfo.getSavePath());
                        loadInfo.setCompleteType("2");
                        loadInfo.setClassId(getIntent().getStringExtra("course_id"));
                        loadInfo.setClassName(getIntent().getStringExtra("item_title"));
                        downloadInfoDao.update(loadInfo);
                    }


                    if (down_layout.getVisibility() == View.VISIBLE) {
                        buildProgressDialog(false);
                        getRalationDownloads();
                    }

//                    for (RalationDownloads.ResultBean resultBean : resultBeanList) {
//                        if (!downloadInfoList.isEmpty() && downloadInfoList.get(0).getUrl().equals(resultBean.getVideo_url())) {
//                            resultBean.setType(3);
//                        }
//                    }
//                    listViewDownAdapter.notifyDataSetChanged();

                    Toast.makeText(LiveRoomNewActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                }
            }
        });
//        DownloadUtil.get().download(url, "老妖精消防", fileName, new DownloadUtil.OnDownloadListener() {
//            @Override
//            public void onDownloadSuccess() {
//                LiveRoomActivity.this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(LiveRoomActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
//                    }
//                });
//            }
//
//            @Override
//            public void onDownloading(int progress) {
////                progressBar.setProgress(progress);
//                System.out.println("onDownloading==:" + progress);
//            }
//
//            @Override
//            public void onDownloadFailed() {
//                LiveRoomActivity.this.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(LiveRoomActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
//                    }
//                });
//
//            }
//        });
    }

    /**
     * 加载框显示
     **/
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void buildProgressDialog(boolean cancelable) {
        if (this.isDestroyed()) {
            return;
        }
        if (progressDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(LiveRoomNewActivity.this);
            builder.setView(R.layout.item_progress_dialog);
            builder.setCancelable(cancelable);
            progressDialog = builder.create();
            progressDialog.show();
        } else {
            progressDialog.show();
        }
    }

    /**
     * 加载框消失
     **/
    public void cancelProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private void setFinish() {
        if (!CommonUtils.isEmpty(playId)) {
            addPlaybackProgress(playId, (videoView.getCurrentPosition() / 1000) + "",
                    (videoView.getDuration() / 1000) + "",
                    "0", getIntent().getStringExtra("course_id"));
        }

        cancelProgressDialog();
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) videoLayout.getLayoutParams();
            linearParams.height = CommonUtils.getScreenHeight(LiveRoomNewActivity.this) / 3;
            linearParams.width = CommonUtils.getScreenWidth(LiveRoomNewActivity.this);
            //切换竖屏
            LiveRoomNewActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

            videoLayout.setLayoutParams(linearParams);
            return;
        }

        LiveRoomNewActivity.super.finish();
    }

    @Override
    public void onBackPressed() {
        setFinish();
    }

    @Override
    protected void onStart() {
        super.onStart();
        System.out.println("onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        System.out.println("onResume");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        System.out.println("onRestart");
        if (!CommonUtils.isEmpty(videoPath)) {
            loadingView.setVisibility(View.VISIBLE);
            fullScreenImage.setVisibility(View.GONE);
            videoView.setVideoPath(videoPath);
            videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mMediaPlayer) {
                    loadingView.setVisibility(View.GONE);
                    fullScreenImage.setVisibility(View.VISIBLE);
                    mediaPlayer = mMediaPlayer;
                    mediaPlayer.start();
                    videoView.seekTo(playCurrent);
                }
            });
        }
        CommonUtils.keepScreenOn(wakeLock, this, true);
        CommonUtils.keepScreenLongLight(this, true);
    }

    @Override
    protected void onStop() {
        super.onStop();
        System.out.println("onStop");
    }

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onPause() {
        super.onPause();
        playCurrent = videoView.getCurrentPosition();
        System.out.println("onPause");
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.out.println("onDestroy");
        if (liveRoom != null) {
            liveRoom.quitRoom();
            liveRoom = null;
        }
        JCVideoPlayer.releaseAllVideos();
        CommonUtils.keepScreenOn(wakeLock, this, false);
        CommonUtils.keepScreenLongLight(this, false);

        if (videoView != null) {
            videoView.stopPlayback();
        }
    }

}
